#include "stdafx.h"
#include "caRMemReadWrite.h"

caCRMemReadWriteByAPI::caCRMemReadWriteByAPI(HANDLE proc)
{
	m_proc=proc;
}

caCRMemReadWriteByAPI::~caCRMemReadWriteByAPI()
{}

DWORD caCRMemReadWriteByAPI::Read(LPCVOID lpAddress, LPVOID lpBuffer, SIZE_T nSize)
{
	DWORD size=0;
	DWORD protect=PAGE_READWRITE;
	MEMORY_BASIC_INFORMATION mbi;

	try
	{
		if(m_proc)
		{
			if(!::ReadProcessMemory(m_proc,lpAddress,lpBuffer,nSize,&size))
			{
				if(::VirtualQueryEx(m_proc,lpAddress,&mbi,nSize))
				{
					if(::VirtualProtectEx(m_proc,(LPVOID)lpAddress,nSize,protect,&protect))
					{
						::ReadProcessMemory(m_proc,lpAddress,lpBuffer,nSize,&size);
						::VirtualProtectEx(m_proc,(LPVOID)lpAddress,nSize,protect,&protect);
					}				
				}

			}
		}
	}
	catch(...)
	{
		return 0;
	}
	return size;
}

DWORD caCRMemReadWriteByAPI::Write(LPVOID lpAddress, LPCVOID lpBuffer, SIZE_T nSize)
{
	DWORD size=0;
	DWORD protect=PAGE_READWRITE;
	MEMORY_BASIC_INFORMATION mbi;

	try
	{
		if(m_proc)
		{
			if(!::WriteProcessMemory(m_proc,lpAddress,lpBuffer,nSize,&size))
			{
				if(::VirtualQueryEx(m_proc,lpAddress,&mbi,nSize))
				{
					if(::VirtualProtectEx(m_proc,(LPVOID)lpAddress,nSize,protect,&protect))
					{
						::WriteProcessMemory(m_proc,lpAddress,lpBuffer,nSize,&size);
						::VirtualProtectEx(m_proc,(LPVOID)lpAddress,nSize,protect,&protect);
					}				
				}

			}
		}
	}
	catch(...)
	{
		return 0;
	}
	return size;
}